/**
 * 流程图只读模式
 */
import "./approveStepReadonly.css"
import React, { useEffect, useMemo, useRef, useState } from "react";
import {  Input, Modal, Button, Spin} from "antd";
import message from "../../framework/common/utils/message";
import request from "../../framework/common/utils/request";
import ApproveStepEdit from "./ApproveStepEdit";/*流程图组件*/
import { submitApproveForm } from "../../components/Footer1/submitApproveForm";//发起审批入口
import eventBus, { useSubscribe } from "../../framework/common/eventBus";
import { validateSteps } from "./stepUtility";
import clsx from "clsx";

export default function({
    showStepEditModal = false,
    actual_steps,//返回给后端的步骤，不包括branch确认信息步骤
    approveSteps,//展示在界面上当步骤，包括branch确认信息步骤
    validateResult = null,
    model = "edit",
    tplData:tplData,
    params:params,
    urlPrefix,
    handleCancel,
    afterStepEditClose,
    handleApprove,//调用父组件事件
    approveType
}){
    const [loading, setLoading] = useState(false);//加载状态
    const [returnSteps, setReturnSteps] = useState(actual_steps);//返回给后端的步骤
    const [allSteps, setAllSteps] = useState(approveSteps);//展示在界面上的步骤，包括branch确认信息步骤
    const [showValidate, setShowValidate] = useState(false);//显示步骤校验信息
    const [passWord, setPassWord] = useState("");//签章密码
    const [passwordStatus, setPasswordStatus] = useState(null);//签章密码错误状态
    
    //流程图显示隐藏
    const [showFlowMap, setShowFlowMap] = useState(false);//流程图显示隐藏
    useSubscribe("showFlowMap.update", function(data){
        setShowFlowMap(data);
    });

    //步骤发生更新时，更新当前组件的步骤信息
    useEffect(function(){
        setReturnSteps(actual_steps)
    }, [actual_steps])

    useEffect(function(){
        setAllSteps(approveSteps)
    }, [approveSteps]);

    //其他组件调用发起审批
    useSubscribe("setStepBtnLoading.update", (data)=>{
        if(data !== undefined){
            setLoading(data);
        }else{//没传data，默认去掉按钮loading状态
            setLoading(false);
        }
    });

    //更新当前组件给到后端当步骤信息
    useSubscribe("setReturnSteps.update", (data)=>{
        setReturnSteps(data);  
    })

    //更新当前组件给到后端当步骤信息
    useSubscribe("setAllSteps.update", (data)=>{
        setAllSteps(data);  
    })

    let enable_sign_pwd = tplData.ProfileSign && tplData.ProfileSign.enable_sign == '1' && tplData.ProfileSign.enable_sign_pwd == '1';//显示签章密码

    //校验签章密码
    function checkSignPwd(){
        if(passWord.trim() == ""){
            setPasswordStatus("error");
            return;
        }
        setLoading(true);
        request({
            url: '/user/signature/check-sign-pwd',
            method: "POST",
            data:{ 
                input_pwd: passWord
            }
        }).then(function(resObj){
            if (resObj.code == 1) {
                if(showValidate){
                    doApprove();
                }else{
                    setShowValidate(true);//显示校验信息
                }
                setPasswordStatus(null);
            } else {
                setLoading(false);
                setPasswordStatus("error");
            }
        },function(){
            setLoading(false);
            message.info({
                content: "签章密码验证失败"
            });
        })
    }

    //确定按钮事件
    function handleOk(){
        if(enable_sign_pwd){//开启了签章密码，先校验密码
            checkSignPwd();
        }else{//没开启就直接发起
            if(showValidate){
                doApprove();
            }else{
                setShowValidate(true);//显示校验信息
            }
        }
    }

    //发起流程
    function doApprove(){
        let validateStep = validateSteps({
            steps: allSteps,
            tplData: tplData
        });//校验流程
        if(!validateStep){
            setLoading(false);
            return;//校验不通过，不做提交
        }

        //提交前当步骤清洗，给每个步骤设置实际勾选的责任人
        returnSteps.forEach(function(step, i) {
            if (
                (
                    (step.stepAttrs && step.stepAttrs.multi_type == 'Single') 
                    || (step.step_type == 2 && step.stepAttrs.archived_mode != 'Auto')
                )
                && !step.is_user_reset_activity
            ) {//单人步骤，只保留一个node
                var choosedStep = null;
                step.nodes.forEach(function(user, index) {
                    if (user.Checked == true || user.Checked == 1) {
                        choosedStep = user;
                    }
                });
                if (choosedStep) {
                    step.nodes = [choosedStep];
                } else {
                    step.nodes = step.nodes.slice(0, 1);
                }
            }else if(
                step.stepAttrs && 
                step.stepAttrs.multi_type == 'Multi' && 
                step.stepAttrs.adjust_multi_auditor && 
                (
                    (
                        step.stepAttrs.no_auditor_rules 
                        && step.stepAttrs.no_auditor_rules.indexOf('SkipStep') == -1) 
                        || step.nodes.length
                )
            ){//多人步骤，保留选中的node
                var nodes = [];
                step.nodes.forEach( function(user, index) {
                    if (user.Checked) {//选中的用户
                        /**
                         * 注：多人步骤分两种情况
                         * 1、不可调整责任人，在stepUtility.js内默认设置Checked=true
                         * 2、可调整责任人，为手动勾选时，设置Checked=true
                         */
                        nodes.push(user);
                    }
                });
                if(nodes.length){
                    step.nodes = nodes;
                }
            }
        });
        
        //测试代码，在控制台打印出每个步骤当审批人信息
        returnSteps.map(function(step){
            /*测试打印信息 */
            console.log("步骤名称：" + step.name)
            var users = [];
            if(step.stepAttrs.multi_type == 'Multi'){//多选
                if(step.stepAttrs.adjust_multi_auditor){//可调整责任人
                    console.log("步骤类型：多人步骤，可调整责任人")
                    step.nodes.map(function(item){
                        if(item.Checked){
                            users.push(item.auditor_name);
                        }
                    });
                }else{
                    console.log("步骤类型：多人步骤，不可调整责任人")
                    step.nodes.map(function(item){
                        users.push(item.auditor_name);
                    });
                }
            }else{
                console.log("步骤类型：单人步骤")
                step.nodes.map(function(item){
                    users.push(item.auditor_name);
                });
            }
            
            console.log("审批人：" + users.join("、"))
            console.log("====================")
        })
        submitApproveForm({
            enable_sign_pwd: tplData.ProfileSign && tplData.ProfileSign.enable_sign == '1' && tplData.ProfileSign.enable_sign_pwd == '1',//签章开启状态
            isValid: "",
            steps: returnSteps,//步骤路径
            tplData: tplData,
            params: params,
            urlPrefix: urlPrefix,
            approveType: approveType,
            setLoading: setLoading//确定按钮的状态方法
        });//发起流程
        
        handleApprove();//调用父组件事件
    }
    useEffect(function(){
        if(showValidate){
            doApprove();
        }
    }, [showValidate]);

    const [stepHasNoError, setStepHasNoError] = useState(validateResult === null);//路径不存在后端错误
    useEffect(function(){
        setStepHasNoError(validateResult === null);//外层组件传递validateResult信息时更新按钮状态
    }, [validateResult])
    useSubscribe("setStepHasNoError.update", (newValidateResult)=>{
        setStepHasNoError(newValidateResult === null);//其他组件发送消息更新状态，发送校验信息即可
    })
    let footerButtons = [];//页脚按钮信息
    if(stepHasNoError && approveSteps?.length){//步骤信息不包含错误信息 && 存在步骤信息
        if(enable_sign_pwd){
            footerButtons = [
                <div 
                    key={"password"}
                    className="flex float-left h-8 leading-8">
                    <p className="inline-flex w-24 m-0">签章密码 <span className="require text-color-f86161">*</span></p>
                    <Input.Password 
                        onChange={(e)=>{
                            setPassWord(e.target.value);
                            if(e.target.value.trim() == ""){
                                setPasswordStatus("error");
                            }else{
                                setPasswordStatus(null);
                            }
                        }}
                        status={passwordStatus}
                        value={passWord}
                        maxLength={6}
                        placeholder="请输入签章密码" 
                        className="w-48"/>
                </div>
            ]
        }
        footerButtons = footerButtons.concat([
            <Button
                key={"cancel"}
                onClick={handleCancel}
            >取消</Button>,
            <Button 
                key={"submit"}
                type="primary"
                loading={loading}
                onClick={handleOk}
            >确定</Button>
        ])
    }else{//步骤信息包含错误信息
        footerButtons = [
            <Button 
                key={"knowIt"}
                type="primary"
                onClick={handleCancel}
            >我知道了</Button>
        ]
    }

    let canShowFlowMap = !tplData.temporaryStepsSetting || (tplData.ApproveSteps.length ? !tplData.temporaryStepsSetting.approve : !tplData.temporaryStepsSetting.initiated);//是否要显示展开流程图

    return <Modal
        visible={showStepEditModal}
        title={<ModalTitle 
                    canShowFlowMap={canShowFlowMap}
                    tplData={tplData}
                    showFlowMap={showFlowMap}
                ></ModalTitle>
              }
        wrapClassName={'approveStep'}
        centered={true}
        width={showFlowMap ? "90%" : 600}
        onCancel={handleCancel}
        footer={footerButtons}
        keyboard={false}
        maskClosable={false}
        afterClose={()=>{
            
        }}
    >
        <ApproveStepEdit
            tplData={tplData} 
            params={params} 
            urlPrefix={urlPrefix}
            model={"edit"}
            actual_steps={actual_steps}
            approveSteps={approveSteps} 
            setLoading={setLoading}
            validateResult={validateResult}
            showValidate={showValidate}
            approveType={approveType}
            canShowFlowMap={canShowFlowMap}
            ></ApproveStepEdit>
        {
            canShowFlowMap
            && <FlowMapIframe
                tplData={tplData}
                showFlowMap={showFlowMap}
                params={params} 
                urlPrefix={urlPrefix}></FlowMapIframe>
        }
    </Modal>
}

//修改业务数据标题
function ModalTitle({
    canShowFlowMap = false,//是否显示流程图
    showFlowMap = false
}){
    if(canShowFlowMap){//
        return <div className="overflow-hidden">
                    确认流程路径
                    <a 
                        className="float-right text-sm mr-5 leading-6"
                        onClick={()=>{
                            // setShowFlowMap(!showFlowMap);
                            eventBus.publish("showFlowMap.update", !showFlowMap);
                        }}
                    >
                        {
                            showFlowMap === true ? "收起流程图" : "展开流程图"
                        }
                    </a>
                </div>
    }

    return <>确认流程路径</>
}

//流程图
function FlowMapIframe({
    urlPrefix,
    params,
    showFlowMap = false//流程图显示隐藏状态
}){
    //流程图显示隐藏状态
    // const [showFlowMap, setShowFlowMap] = useState(false);
    /**
     * 更新流程图显示隐藏状态
     */
    // useSubscribe("showFlowMap.update", function(data){
    //     setShowFlowMap(data);
    // });

    const [initLoad, setInitLoad] = useState(false);//初次加载
    const [iframeLoad, setIframeLoad] = useState(true);//iframe loading状态

    let iframeRef = useRef(null);
    useSubscribe("selectFlowMapStep.update", ()=>{
        iframeRef.current?.contentWindow?.vue?.handleSelectStep();
    });
    useSubscribe("handlestepsPath,update", ()=>{
        iframeRef.current?.contentWindow?.vue?.handlestepsPath();
    })

    let iframSrc = useRef("");
    useEffect(function(){
        var proc_id="00000000-0000-0000-0000-3A00918E9790";
        if( params.proc_id !="" &&  params.proc_id != null){
            proc_id= params.proc_id;
        }
        var iframeHref = '/flowinstance/process/get-initiate-steps-map?flow_template_id=' + params.flow_template_id+ "&flow_id=" + proc_id;
        if(urlPrefix){
            iframeHref = urlPrefix + iframeHref;
        }
        iframSrc.current = iframeHref;
    },[]);

    //不显示流程图 && 还未加载过，不生成iframe，也就是第一次打开弹框，不要加载iframe
    if(!showFlowMap && !initLoad){
        return null;
    }

    //显示流程图 && 还未加载过，把初次加载设置为true，并且返回null，更新状态会再次进入，再次进入时，加载iframe
    if(showFlowMap && !initLoad){
        setInitLoad(true);
        return null;
    }

    if(showFlowMap){
        setTimeout(function(){
            iframeRef.current?.contentWindow?.vue?.handleSelectStep();
        }, 300);
    }

    return <div className={clsx("flowMapIframe absolute left-600 top-0 bottom-0 right-6", !showFlowMap && "hidden")}>
                <Spin spinning={iframeLoad}>
                    <iframe
                        ref={iframeRef}
                        width="100%"
                        height="100%"
                        name="flowIframe"
                        onLoad={(e)=>{
                            e.target.contentWindow.vue.handleSelectStep();
                            setIframeLoad(false);
                        }}
                        src={iframSrc.current}></iframe>
                </Spin>
            </div>
}